package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.github.pagehelper.PageInfo;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessDic.BusinessDicModifyRequest;
import com.ktwlsoft.archivemanage.payload.businessDic.BusinessDicSaveRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务字段
 *
 * @author zhuhe on 2019/10/25 15:42
 * @version 1.0
 */
@Component
public class BusinessFieldService {

    /**业务字段*/
    private final BusinessDicRepositoryService businessDicRepositoryService;

    /**室藏档案*/
    private final UnitArchivesRepositoryService unitArchivesService;

    /**立档单位*/
    private final ArchiveUnitRepositoryService archiveUnitService;

    /**单位人员*/
    private final UnitMemberRepositoryService unitMemberService;

    public BusinessFieldService(BusinessDicRepositoryService businessDicRepositoryService, UnitArchivesRepositoryService unitArchivesService, ArchiveUnitRepositoryService archiveUnitService, UnitMemberRepositoryService unitMemberService) {
        this.businessDicRepositoryService = businessDicRepositoryService;
        this.unitArchivesService = unitArchivesService;
        this.archiveUnitService = archiveUnitService;
        this.unitMemberService = unitMemberService;
    }
    
    /**
      * 业务字段列表 on 2019/10/25 15:46
      *
      * @param pn pn
      * @param pageSize pageSize
      * @param dicType dicType
      * @return Result<?>
      */
    public Result<?> findPage(int pn,int pageSize,BusinessDic.dicType dicType){
        BusinessDic businessDic = new BusinessDic();
        if(dicType != null) {
            businessDic.setDicType(dicType);
        }
        businessDic.setId(null);
        businessDic.setCreatedAt(null);
        businessDic.setCreatorId(null);
        businessDic.setCreator(null);
        businessDic.setUpdateAt(null);
        PageInfo<BusinessDic> pageInfo = businessDicRepositoryService.findPage(pn,pageSize,businessDic);
        return Result.ok(pageInfo);
    }

    /**
     * 业务字段新增 on 2019/10/24 17:02
     *
     * @return ResponseEntity<?>
     */
    public Result<?> save(BusinessDicSaveRequest request){
        BusinessDic businessDic = new BusinessDic();
        BeanUtils.copyProperties(request,businessDic);
        if(handelValue(businessDic)){
            return Result.body(request.getDicValue(),ResultType.CHECK_ERROR).withMessage("该字段值已存在并启用");
        }
        try {
            businessDicRepositoryService.insert(businessDic);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(businessDic.getId());
    }

    /**
      * 业务字段修改 on 2019/10/25 16:02
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> modify(BusinessDicModifyRequest request){
        BusinessDic businessDic = businessDicRepositoryService.getById(request.getId());
        if(businessDic == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(handelValue(businessDic)){
            return Result.body(request.getDicValue(),ResultType.CHECK_ERROR).withMessage("该字段值已存在并启用");
        }
        businessDic.setDicValue(request.getDicValue());
        try {
            businessDicRepositoryService.update(businessDic);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null,ResultType.UPDATE_ERROR);
        }
        return Result.ok(businessDic.getId());
    }

    /**
      * 业务字段删除 on 2019/10/25 16:20
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> deleteById(Long id){
        if(id == null || id <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessDic businessDic = businessDicRepositoryService.getById(id);
        if(businessDic == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(!businessDic.getDeletable()){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该字段不可删除");
        }
        if(businessDic.getDicType() != null){
            switch (businessDic.getDicType()){
                case ARCHIVE_TYPE:
                    //档案类型
                    UnitArchives archives = new UnitArchives();
                    archives.setArchiveType(businessDic.getId());
                    archives.setId(null);
                    archives.setCreatedAt(null);
                    archives.setUpdateAt(null);
                    archives.setCreator(null);
                    archives.setCreatorId(null);
                    List<UnitArchives> unitArchives = unitArchivesService.findList(archives);
                    if(unitArchives != null && unitArchives.size() > 0){
                        return Result.body(null, ResultType.CHECK_ERROR).withMessage("无法删除,该数据已被引用");
                    }
                    break;
                case UNIT_NATURE:
                    //单位性质
                    ArchiveUnit archiveUnit = new ArchiveUnit();
                    archiveUnit.setUnitNature(businessDic.getDicValue());
                    archiveUnit.setId(null);
                    archiveUnit.setCreatedAt(null);
                    archiveUnit.setUpdateAt(null);
                    archiveUnit.setCreator(null);
                    archiveUnit.setCreatorId(null);
                    List<ArchiveUnit> archiveUnits = archiveUnitService.findList(archiveUnit);
                    if(archiveUnits != null && archiveUnits.size() > 0){
                        return Result.body(null, ResultType.CHECK_ERROR).withMessage("无法删除,该数据已被引用");
                    }
                    break;
                case WORK_TYPE:
                    //在岗类型
                    UnitMember member = new UnitMember();
                    member.setRecorderWorkType(businessDic.getDicValue());
                    member.setId(null);
                    member.setCreatedAt(null);
                    member.setUpdateAt(null);
                    member.setCreator(null);
                    member.setCreatorId(null);
                    List<UnitMember> members = unitMemberService.findList(member);
                    if(members != null && members.size() > 0){
                        return Result.body(null, ResultType.CHECK_ERROR).withMessage("无法删除,该数据已被引用");
                    }
                    break;
                case EDUCATE_DEGREE:
                    //文化程度
                    UnitMember unitMember = new UnitMember();
                    unitMember.setRecorderEducate(businessDic.getDicValue());
                    unitMember.setId(null);
                    unitMember.setCreatedAt(null);
                    unitMember.setUpdateAt(null);
                    unitMember.setCreator(null);
                    unitMember.setCreatorId(null);
                    List<UnitMember> unitMembers = unitMemberService.findList(unitMember);
                    if(unitMembers != null && unitMembers.size() > 0){
                        return Result.body(null, ResultType.CHECK_ERROR).withMessage("无法删除,该数据已被引用");
                    }
                    break;
                    default:
            }
        }
        try {
            businessDicRepositoryService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.DELETE_ERROR);
        }
        return Result.ok(businessDic.getDicValue());
    }

    /**
      * 业务字段启用禁用 on 2019/10/25 16:24
      *
      * @param id id
      * @return Result<?>
      */
    public Result<?> enableById(Long id){
        if(id == null || id <= 0){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        BusinessDic businessDic = businessDicRepositoryService.getById(id);
        if(businessDic == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(handelValue(businessDic)){
            return Result.body(businessDic.getDicValue(),ResultType.CHECK_ERROR).withMessage("该字段值已存在并启用");
        }
        businessDic.setEnable(!businessDic.getEnable());
        try {
            businessDicRepositoryService.update(businessDic);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        if(businessDic.getEnable()){
            saveLog(OperationLog.OperationType.ENABLE,"启用业务字段《" + businessDic.getDicValue() + "》");
        }else{
            saveLog(OperationLog.OperationType.DISABLE,"禁用业务字段《" + businessDic.getDicValue() + "》");
        }
        return Result.ok(businessDic.getDicValue());
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description 描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description){
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "业务字段",
                OperationLog.BusinessType.SYSTEM
        ));
    }

    /**
      * 处理value on 2019/11/5 9:46
      *
      * @param businessDic businessDic
      * @return 字段存在true,不存在false
      */
    private boolean handelValue(BusinessDic businessDic){
        if(businessDic.getDicType() == null || businessDic.getDicValue() == null || "".equals(businessDic.getDicValue())){
            return false;
        }
        List<BusinessDic> businessDics = businessDicRepositoryService.getByDicValue(businessDic);
        if(businessDics != null && businessDics.size() > 0){
            for(BusinessDic dic:businessDics){
                if(dic.getEnable() && !dic.getId().equals(businessDic.getId())){
                    return true;
                }
            }
        }
        return false;
    }
}